# -*-coding:utf-8-*-

import wx, os, sys, time
import wx.lib.buttons as buttons
import logConfig as log
from pressureFunc import *
from protocol import *

# 静态标签控件
class StaticLabel(wx.StaticText):
    labelDelta = 1

    def __init__(self, parent, id=-1, label=u'标签', font="", color="#000000", bgColor="", align="center",
                 pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="StaticLabel"):
        cstyle = style
        if cstyle & wx.BORDER_MASK == 0:
            cstyle |= wx.BORDER_NONE
        wx.StaticText.__init__(self, parent, id, "", pos, size, cstyle, name)

        if font:
            self.SetFont(font)
        else:
            self.SetFont(self.GetFont())
        self.SetForegroundColour(color) if color != "#000000" else{}
        self.SetBackgroundColour(bgColor) if not (bgColor == "") else{}

        self.up = True
        self.hasFocus = False
        self.style = style
        self.align = align
        self.SetLabel(label)
        self.InheritAttributes()
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda evt: None)

    def SetInitialSize(self, size=None):
        if size is None:
            size = wx.DefaultSize
        wx.PyControl.SetInitialSize(self, size)

    SetBestSize = SetInitialSize

    def DoGetBestSize(self):
        defSize = wx.Button.GetDefaultSize()
        width = defSize.width
        height = defSize.height
        return (width, height)

    def DrawLabel(self, dc, width, height, dx=0, dy=0):
        dc.SetFont(self.GetFont())
        if self.IsEnabled():
            dc.SetTextForeground(self.GetForegroundColour())
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        label = self.GetLabel()
        tw, th = dc.GetTextExtent(label)
        if not self.up:
            dx = dy = self.labelDelta
        # dc.DrawText(label, (width-tw)/2+dx, (height-th)/2+dy)
        if (self.align == "center"):
            dc.DrawText(label, (width - tw) / 2 + dx, (height - th) / 2 + dy)
        elif (self.align == "left"):
            dc.DrawText(label, 30 + dx, (height - th) / 2 + dy)
        elif (self.align == "right"):
            dc.DrawText(label, width - tw - 30 + dx, (height - th) / 2 + dy)
        elif (self.align == "left_0"):
            dc.DrawText(label, dx, (height - th) / 2 + dy)
        elif (self.align == "right_0"):
            dc.DrawText(label, width - tw + dx, (height - th) / 2 + dy)
        elif (self.align == "left_10"):
            dc.DrawText(label, 10 + dx, (height - th) / 2 + dy)
        else:
            pass

    def OnPaint(self, event):
        (width, height) = self.GetClientSizeTuple()

        dc = wx.PaintDC(self)
        brush = self.GetBackgroundBrush(dc)
        if brush is not None:
            dc.SetBackground(brush)
            dc.Clear()
        self.DrawLabel(dc, width, height)

    def GetBackgroundBrush(self, dc):
        colBg = self.GetBackgroundColour()
        brush = wx.Brush(colBg, wx.SOLID)
        if self.style & wx.BORDER_NONE:
            myAttr = self.GetDefaultAttributes()
            parAttr = self.GetParent().GetDefaultAttributes()
            myDef = colBg == myAttr.colBg
            parDef = self.GetParent().GetBackgroundColour() == parAttr.colBg
            if myDef and parDef:
                if wx.Platform == "__WXMAC__":
                    c = wx.MacThemeColour(1)  # 1 == kThemeBrushDialogBackgroundActive
                    brush = wx.Brush(c)
                elif wx.Platform == "__WXMSW__":
                    if self.DoEraseBackground(dc):
                        brush = None
            elif myDef and not parDef:
                colBg = self.GetParent().GetBackgroundColour()
                brush = wx.Brush(colBg, wx.SOLID)
        return brush

# 文字按钮
class ButtonWord(wx.Button):
    def __init__(self, parent, id=-1, label=u'按钮', font="", color="#000000", bgColor="#ffffff", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.BORDER_NONE, validator=wx.DefaultValidator, name="ButtonCommon"):
        wx.Button.__init__(self, parent, id, label, pos, size, style, validator, name)
        self.SetForegroundColour(color) if color != "#000000" else {}
        self.SetBackgroundColour(bgColor) if bgColor != "#ffffff" else {}
        if font:
            self.SetFont(font)
        else:
            self.SetFont(self.GetFont())

class StaticTextCtrl(wx.TextCtrl):
    labelDelta = 1
    def __init__(self, parent, id=-1, text="", font="", color="#000000", bgColor="#ffffff", align="center", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.BORDER_NONE, validator=wx.DefaultValidator, name="textCtrlCommon"):
        wx.TextCtrl.__init__(self, parent, id, text, pos, size, style, validator, name)
        self.SetForegroundColour(color) if color != "#000000" else {}
        self.SetBackgroundColour(bgColor) if bgColor != "#ffffff" else {}
        if font:
            self.SetFont(font)
        else:
            self.SetFont(self.GetFont())
        self.up = True
        self.style = style
        self.align = align
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def DrawLabel(self, dc, width, height, dx=0, dy=0):
        dc.SetFont(self.GetFont())
        if self.IsEnabled():
            dc.SetTextForeground(self.GetForegroundColour())
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        label = self.GetLabel()
        tw, th = dc.GetTextExtent(label)
        if not self.up:
            dx = dy = self.labelDelta
        # dc.DrawText(label, (width-tw)/2+dx, (height-th)/2+dy)
        if (self.align == "center"):
            dc.DrawText(label, (width - tw) / 2 + dx, (height - th) / 2 + dy)
        elif (self.align == "left"):
            dc.DrawText(label, 30 + dx, (height - th) / 2 + dy)
        elif (self.align == "right"):
            dc.DrawText(label, width - tw - 30 + dx, (height - th) / 2 + dy)
        elif (self.align == "left_0"):
            dc.DrawText(label, dx, (height - th) / 2 + dy)
        elif (self.align == "right_0"):
            dc.DrawText(label, width - tw + dx, (height - th) / 2 + dy)
        elif (self.align == "left_10"):
            dc.DrawText(label, 10 + dx, (height - th) / 2 + dy)
        else:
            pass

    def OnPaint(self, event):
        (width, height) = self.GetClientSizeTuple()

        dc = wx.PaintDC(self)
        brush = self.GetBackgroundBrush(dc)
        if brush is not None:
            dc.SetBackground(brush)
            dc.Clear()
        self.DrawLabel(dc, width, height)

    def GetBackgroundBrush(self, dc):
        colBg = self.GetBackgroundColour()
        brush = wx.Brush(colBg, wx.SOLID)
        if self.style & wx.BORDER_NONE:
            myAttr = self.GetDefaultAttributes()
            parAttr = self.GetParent().GetDefaultAttributes()
            myDef = colBg == myAttr.colBg
            parDef = self.GetParent().GetBackgroundColour() == parAttr.colBg
            if myDef and parDef:
                if wx.Platform == "__WXMAC__":
                    c = wx.MacThemeColour(1)  # 1 == kThemeBrushDialogBackgroundActive
                    brush = wx.Brush(c)
                elif wx.Platform == "__WXMSW__":
                    if self.DoEraseBackground(dc):
                        brush = None
            elif myDef and not parDef:
                colBg = self.GetParent().GetBackgroundColour()
                brush = wx.Brush(colBg, wx.SOLID)
        return brush

# 压力测试控件
class panel_funcTest(wx.Panel):
    def __init__(self, parent, cpu, testInterface='', testType='', testFunc='', testNum="", testCondition='', pos=(0,0), size=(400,170)):
        self.cpu = cpu
        self.testInterface = testInterface
        wx.Panel.__init__(self, parent, -1, pos, size, style=wx.BORDER_DOUBLE)
        self.SetBackgroundColour("#f1f1f1")
        font_bold = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)

        self.title = StaticLabel(self, -1, testType, font=font_bold, color='#ffffff', bgColor="#447ed9", pos=(0,0),size=(400,30))
        self.funcTitle = StaticLabel(self, -1, u"压测功能：", bgColor="#4ebaf8", pos=(0,30), size=(100,30))
        self.funcContent = StaticLabel(self, -1, testFunc, bgColor='#ffffff', pos=(100,30), size=(300,30), align='left')
        self.numTitle = StaticLabel(self, -1, u"压测数量：", bgColor="#2fa7ee", pos=(0,60), size=(100,30))
        self.numContent = wx.TextCtrl(self, -1, testNum, pos=(100,65), size=(300,20), style=wx.TE_RICH)
        #self.numContent = StaticTextCtrl(self, -1, testNum, pos=(100,60), size=(300,30), style=wx.TE_RICH)

        self.conTitle = StaticLabel(self, -1, u"压测条件：", bgColor="#4ebaf8", pos=(0,90), size=(100,30))
        self.conContent = StaticLabel(self, -1, testCondition, bgColor='#ffffff', pos=(100,90), size=(300,30), align='left')

        self.startButton = ButtonWord(self, -1, u"开始测试", color="#ffffff", bgColor="#398bfb", pos=(25,130), size=(150,30))
        self.detailButton = ButtonWord(self, -1, u"测试流程", color="#ffffff", bgColor="#398bfb", pos=(215,130), size=(150,30))
        self.startButton.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.detailButton.SetCursor(wx.StockCursor(wx.CURSOR_MAGNIFIER))
        self.Bind(wx.EVT_BUTTON, self.OnStartBtnClick, self.startButton)
        self.Bind(wx.EVT_BUTTON, self.OnDetailBtnClick, self.detailButton)

    def OnStartBtnClick(self, event):
        num = self.numContent.GetValue()
        PT_testInterface(self.testInterface, self.cpu, int(num))

    def OnDetailBtnClick(self, event):
        if self.testInterface == 'company_createUser':
            log.TestLog(u"创建用户的测试详情如下...")
        elif self.testInterface == 'company_deleteUser':
            log.TestLog(u"删除用户的测试详情如下...")
        elif self.testInterface == 'intercom_httpLogin':
            log.TestLog(u"HTTP登录接口...")
        elif self.testInterface == 'intercom_httpGetGroupQuery':
            log.TestLog(u"HTTP群组信息查询接口")
        elif self.testInterface == 'intercom_httpGetAllGroupMember':
            log.TestLog(u"获取所有群组与成员信息...")
        elif self.testInterface == 'intercom_inVoiceChannel':
            log.TestLog(u"进入语音频道...")
        elif self.testInterface == 'getOnlineNumMax':
            log.TestLog(u"获取能同时在线的对讲机最大数")
        else:
            pass

# 账号创建控件
class panel_companyAccountAdd(wx.Panel):
    def __init__(self, parent, cpu, testInterface='', title=u'', pos=(0,0), size=(250,190)):
        self.cpu = cpu
        self.testInterface = testInterface
        wx.Panel.__init__(self, parent, -1, pos, size, style=wx.BORDER_DOUBLE)
        self.SetBackgroundColour("#f1f1f1")
        font_12 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        font_14 = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.SetFont(font_12)

        self.title = StaticLabel(self, -1, title, font=font_14, color='#ffffff', bgColor="#777777", pos=(0,0),size=(250,30))
        self.Label_companyAccount     = StaticLabel(self, -1, u"企业账号：", color="#ffffff", bgColor="#4ebaf8", pos=(0,30), size=(100,30))
        self.Label_companyPassword     = StaticLabel(self, -1, u"企业密码：", color="#ffffff", bgColor="#4ebaf8", pos=(0,61), size=(100,30))
        self.Label_companyStartSerial     = StaticLabel(self, -1, u"起始编号：", color="#ffffff", bgColor="#4ebaf8", pos=(0,92), size=(100,30))
        self.Label_companyEndSerial     = StaticLabel(self, -1, u"结束编号：", color="#ffffff", bgColor="#4ebaf8", pos=(0,123), size=(100,30))

        self.TextCtrl_companyAccount = wx.TextCtrl(self, -1, "autoTest7", pos=(100,30), size=(150,30), style=wx.TE_RICH)
        self.TextCtrl_companyPassword = wx.TextCtrl(self, -1, "123456", pos=(100,61), size=(150,30), style=wx.TE_RICH)
        self.TextCtrl_companyStartSerial = wx.TextCtrl(self, -1, "10001", pos=(100,92), size=(150,30), style=wx.TE_RICH)
        self.TextCtrl_companyEndSerial = wx.TextCtrl(self, -1, "11000", pos=(100,123), size=(150,30), style=wx.TE_RICH)

        self.startButton = ButtonWord(self, -1, u"开始创建", color="#ffffff", bgColor="#398bfb", pos=(50,155), size=(150,30))

        self.startButton.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Bind(wx.EVT_BUTTON, self.OnStartBtnClick, self.startButton)

    def OnStartBtnClick(self, event):
        companyAccount = self.TextCtrl_companyAccount.GetValue()
        companyPassword = self.TextCtrl_companyPassword.GetValue()
        companyStartSerial = self.TextCtrl_companyStartSerial.GetValue()
        companyEndSerial = self.TextCtrl_companyEndSerial.GetValue()

        PT_company_createUser_single(self.cpu, companyAccount, companyPassword, companyStartSerial, companyEndSerial)
        self.startButton.Enable(False)

# 账号创建控件
class panel_terminalOnline(wx.Panel):
    def __init__(self, parent, cpu, testInterface='', title=u'', pos=(0, 0), size=(250, 190)):
        self.cpu = cpu
        self.testInterface = testInterface
        wx.Panel.__init__(self, parent, -1, pos, size, style=wx.BORDER_DOUBLE)
        self.SetBackgroundColour("#f1f1f1")
        font_12 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        font_14 = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.SetFont(font_12)

        self.ssh_hostname = '114.55.176.110'
        self.ssh_username = 'fnadmin'
        self.ssh_password = 'fn!@#fn123$%^&*'
        self.ssh_port = 15388

        self.title = StaticLabel(self, -1, title, font=font_14, color='#ffffff', bgColor="#777777", pos=(0, 0), size=(250, 30))
        self.Label_companyAccount = StaticLabel(self, -1, u"企业账号：", color="#ffffff", bgColor="#4ebaf8", pos=(0, 30), size=(100, 30))
        self.Label_companyPassword = StaticLabel(self, -1, u"企业密码：", color="#ffffff", bgColor="#4ebaf8", pos=(0, 61), size=(100, 30))
        self.Label_userOnlineNum = StaticLabel(self, -1, u"登录数量：", color="#ffffff", bgColor="#4ebaf8", pos=(0, 92), size=(100, 30))

        self.TextCtrl_companyAccount = wx.TextCtrl(self, -1, "autoTest7", pos=(100, 30), size=(150, 30), style=wx.TE_RICH)
        self.TextCtrl_companyPassword = wx.TextCtrl(self, -1, "123456", pos=(100, 61), size=(150, 30), style=wx.TE_RICH)
        self.TextCtrl_userOnlineNum = wx.TextCtrl(self, -1, "100", pos=(100, 92), size=(150, 30), style=wx.TE_RICH)

        self.startButton = ButtonWord(self, -1, u"发起登录", color="#ffffff", bgColor="#398bfb", pos=(50, 155), size=(150, 30))
        self.startButton.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Bind(wx.EVT_BUTTON, self.OnStartBtnClick, self.startButton)

    def OnStartBtnClick(self, event):
        companyAccount = self.TextCtrl_companyAccount.GetValue()
        companyPassword = self.TextCtrl_companyPassword.GetValue()
        companyUserOnlineNum = self.TextCtrl_userOnlineNum.GetValue()
        companyCode = ""
        if companyAccount == "autoTest7":
            companyCode = "aoTest7"
        elif companyAccount == "autoTest6":
            companyCode = "aoTest6"
        elif companyAccount == "autoTest5":
            companyCode = "aoTest5"
        elif companyAccount == "autoTest4":
            companyCode = "aoTest4"
        elif companyAccount == "autoTest3":
            companyCode = "aoTest3"
        elif companyAccount == "autoTest2":
            companyCode = "aoTest2"
        elif companyAccount == "autoTest1":
            companyCode = "aoTest1"
        else:
            pass

        self.tool_userOnline(companyCode, companyPassword, companyUserOnlineNum)
        self.startButton.Enable(False)

    def tool_userOnline(self, companyCode, password, num):
        ssh = paramiko.SSHClient()  # 创建SSHClient
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 设置连接的远程主机没有本地主机秘钥或HostKeys对象时的策略
        ssh.connect(hostname=self.ssh_hostname, port=self.ssh_port, username=self.ssh_username, password=self.ssh_password)  # 建立SSHClient连接

        stdin, stdout, stderr = ssh.exec_command("echo 'fn!@#fn123$%^&*'|ps -ef|grep testflow.py|grep -v grep|awk '{print $2}'")
        testflow_PID = stdout.read()
        log.TestLog("the process id is:" + str(testflow_PID))
        if testflow_PID:
            log.TestLog("Start to kill the process in linux system!")
            stdin, stdout, stderr = ssh.exec_command("echo 'fn!@#fn123$%^&*'|sudo -S kill -9 " + testflow_PID)
            log.TestLog("End to kill the process in linux system!")
            time.sleep(35)
            log.TestLog("Start to execute the process in linux system! companyCode:" + companyCode + " password:" + str(password) + " num:" + str(num))
            stdin, stdout, stderr = ssh.exec_command("python /home/fnadmin/workPathForFan/linux_autoTest/testflow.py "+companyCode+" "+password+" "+str(num)+" &")
            log.TestLog("End to execute the process in linux system!")
        else:
            log.TestLog("Start to execute the process in linux system! companyCode:" + companyCode + " password:" + str(password) + " num:" + str(num))
            stdin, stdout, stderr = ssh.exec_command("python /home/fnadmin/workPathForFan/linux_autoTest/testflow.py "+companyCode+" "+password+" "+str(num)+" &")
            log.TestLog("End to execute the process in linux system!")
        ssh.close()

# 调度台模拟控件
class panel_dispatch_simulation(wx.Panel):
    def __init__(self, parent, cpu, username, password, pos=(0,0), size=(800,530)):
        self.cpu = cpu
        self.username = username
        self.password = password
        self.uid = 0
        self.gid = 0
        self.groupId = 0
        self.cmpid = 0
        self.key = ''
        self.groupList = ""
        self.memberList = ""
        self.singleCallId = 0
        self.tempGroupId = 0
        self.selectMemberList = {}
        self.userType = 1
        self.websocket = None
        self.rtpSocket = None

        wx.Panel.__init__(self, parent, -1, pos, size, style=wx.BORDER_DOUBLE)
        self.SetBackgroundColour("#f1f1f1")
        font_bold = wx.Font(16, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        font_12 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        font_16 = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.SetFont(font_12)
        self.title = StaticLabel(self, -1, u"模拟调度台", font=font_bold, color='#ffffff', bgColor="#777777", pos=(0,0),size=(800,30))
        self.Label_username = StaticLabel(self, -1, u"账号：", color="#ffffff", bgColor="#4ebaf8", pos=(0,32), size=(100,30))
        self.TextCtrl_username = wx.TextCtrl(self, -1, self.username, pos=(100,32), size=(200,30), style=wx.TE_RICH)
        self.Label_password = StaticLabel(self, -1, u"密码：", color="#ffffff", bgColor="#2fa7ee", pos=(300,32), size=(100,30))
        self.TextCtrl_password = wx.TextCtrl(self, -1, self.password, pos=(400,32), size=(200,30), style=wx.TE_RICH)
        self.Btn_login = ButtonWord(self, -1, u"登录", color="#ffffff", bgColor="#398bfb", pos=(605, 32), size=(190, 30))

        self.Label_groupList = StaticLabel(self, -1, u"群组信息：", bgColor="#4ebaf8", pos=(0, 64), size=(250, 30))
        self.Label_memberList = StaticLabel(self, -1, u"成员信息：", bgColor="#4ebaf8", pos=(275, 64), size=(250, 30))
        self.Label_operateList = StaticLabel(self, -1, u"操作终端：", bgColor="#4ebaf8", pos=(550, 64), size=(250, 30))

        self.ListBox_groupList = wx.ListBox(self, -1, (0,96), (250, 400), '', wx.LB_SINGLE)
        self.ListBox_memberList = wx.ListBox(self, -1, (275,96), (250, 400), '', wx.LB_MULTIPLE)
        self.ListBox_operateList = wx.ListBox(self, -1, (550, 96), (250, 400), '', wx.LB_SINGLE)

        self.Btn_getMember = ButtonWord(self, -1, u">", color="#ffffff", bgColor="#398bfb", pos=(250,286), size=(25,25))
        self.Btn_addMember = ButtonWord(self, -1, u">", color="#ffffff", bgColor="#398bfb", pos=(525,286), size=(25,25))

        self.Btn_singleCall = ButtonWord(self, -1, u"单呼", color="#ffffff", bgColor="#398bfb", pos=(0,498), size=(190,30))
        self.Btn_temporaryGroup = ButtonWord(self, -1, u"临时组", color="#ffffff", bgColor="#398bfb", pos=(200,498), size=(190,30))
        self.Btn_broadcast = ButtonWord(self, -1, u"广播", color="#ffffff", bgColor="#398bfb", pos=(400,498), size=(190,30))
        self.Btn_ptt = ButtonWord(self, -1, u"发送语音", color="#ffffff", bgColor="#398bfb", pos=(610,498), size=(190,30))

        self.TextCtrl_username.SetFont(font_16)
        self.TextCtrl_password.SetFont(font_16)
        self.Btn_getMember.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_addMember.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_login.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_singleCall.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_temporaryGroup.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_broadcast.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_ptt.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

        self.Btn_singleCall.Enable(False)
        self.Btn_temporaryGroup.Enable(False)
        self.Btn_broadcast.Enable(False)
        self.Btn_ptt.Enable(False)

        self.Bind(wx.EVT_BUTTON, self.OnBtn_getMemberClick, self.Btn_getMember)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_addMemberClick, self.Btn_addMember)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_loginClick, self.Btn_login)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_singleCallClick, self.Btn_singleCall)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_temporaryGroupClick, self.Btn_temporaryGroup)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_broadcastClick, self.Btn_broadcast)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_pttClick, self.Btn_ptt)

    def OnBtn_loginClick(self, event):
        if self.Btn_login.GetLabel() == u"已登录":
            log.TestLog(u"账号已经登录...","F")
            return
        log.TestLog(u"模拟调度台开始登录...")
        self.username = self.TextCtrl_username.GetValue()
        self.password = self.TextCtrl_password.GetValue()
        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/login.do', getLoginMsg(self.username, self.password, self.userType))
        if response["status"] == 'success':
            self.uid = response["content"]["body"]["userid"]
            self.cmpid = response["content"]["body"]["companyId"]
            self.key = response["content"]["body"]["userToken"]
            self.Btn_login.SetBackgroundColour("#ff0000")
            self.Btn_login.SetLabel(u"已登录")
            log.TestLog(u"模拟调度台登录成功...")

        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/groupQuery.do', getGroupQueryMsg(self.uid, self.cmpid, self.userType, '', self.key))
        if response["status"] == 'success':
            self.groupList = json.loads(response["content"]["body"])
            for group in self.groupList:
                self.ListBox_groupList.Append(group["groupName"])

        log.TestLog(u"开始建立Websocket来进行TCP通信")
        self.websocket = webSocket(self.cpu, self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], 8087, 'fn-ws', self.cmpid, self.uid, self.password, self.key)
        #log.info(u"发起TCP接入请求1——>8001")
        times = 0
        while True:
            if(self.websocket.statCon == True):
                log.TestLog(u"Websocket创建成功，开始发起TCP接入请求...")
                self.websocket.wsTcpSend(assemblyTCPData(1, 1, 1, getAccessMsg(self.cmpid, self.uid, md5(self.password), self.userType, FN_KEY)))
                break
            else:
                if times > 2000:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        #log.info(u"创建心跳线程2——>8002")
        times = 0
        while True:
            if(self.websocket.statTcpIn == True):
                log.TestLog(u"TCP接口成功，开启心跳线程...")
                thread_heartbeat = threading.Thread(target=heartbeat, args=(self.websocket, self.cmpid, self.uid, self.websocket.token))
                thread_heartbeat.start()
                break
            else:
                if times > 2000:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

    def OnBtn_getMemberClick(self, event):
        groupName = self.ListBox_groupList.GetStringSelection()
        if groupName == "":
            log.TestLog(u"未选择查询组，请确认后再操作...")
            return
        self.ListBox_memberList.Clear()

        for group in self.groupList:
            if groupName == group["groupName"]:
                self.groupId = group["groupId"]
        log.TestLog(u"查询选中组【"+groupName+u"】中的成员...")
        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/groupMemberQuery.do',getGroupMemberQueryMsg(self.uid, self.groupId, self.cmpid, self.userType, self.key))
        if response["status"] == "success":
            #self.memberList = json.loads(response["content"]["body"])
            self.memberList = response["content"]["body"]
            for member in self.memberList:
                self.ListBox_memberList.Append(member["username"])

    def OnBtn_addMemberClick(self, event):
        addIndex = self.ListBox_memberList.GetSelections()
        if str(addIndex) == "()":
            log.TestLog(u"未选择操作成员，请确认后再操作...")
            return
        for index in addIndex:
            addName = self.ListBox_memberList.GetString(index)
            for member in self.memberList:
                if addName == member["username"]:
                    if not self.selectMemberList.has_key(member["userid"]):
                        self.selectMemberList[member["userid"]] = member["username"]
                        self.ListBox_operateList.Append(addName)

                        self.Btn_singleCall.Enable(True)
                        self.Btn_temporaryGroup.Enable(True)
                        self.Btn_broadcast.Enable(True)

                        log.TestLog(u"增加操作成员【" + addName + u"】，...")
                    else:
                        log.TestLog(u"操作成员【"+addName+u"】已经存在","F")

    def OnBtn_singleCallClick(self, event):
        if self.Btn_singleCall.GetLabel() == u"单呼":
            log.TestLog(u"模拟调度台开始发起单呼...")
            log.TestLog(u"开始创建临时组...")
            name = self.ListBox_operateList.GetStringSelection()
            for member in self.selectMemberList:
                if name == self.selectMemberList[member]:
                    self.singleCallId = member

            response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/group/createTemporaryGroup.do', getCreateTemporaryGroupMsg(self.uid,self.userType,self.cmpid,self.key,self.cpu["data"]._const["TEMPGROUP_TYPE"]["singleCall"], self.singleCallId))
            if response["status"] ==  'success':
                self.gid = response["content"]["body"]
                log.TestLog(u"临时组创建成功...")
            else:
                log.TestLog(u"临时组创建失败...")
                return

            log.TestLog(u"开始发起音视频单呼...")
            self.websocket.wsTcpSend(assemblyTCPData(7,1,1,getVideoSingleCallMsg(self.cmpid, self.uid, self.singleCallId, self.gid)))

            times = 0
            while True:
                if(self.websocket.statSingleCall == True):
                    log.TestLog(u"单呼发起成功，进入语音频道")
                    self.websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(self.cmpid, self.uid, self.gid, self.cpu["data"].videoType[3])))
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

            times = 0
            while True:
                if(self.websocket.statInChannel == True):
                    log.TestLog(u"成功进入语音频道")
                    self.Btn_singleCall.SetBackgroundColour("#ff0000")
                    self.Btn_singleCall.SetLabel(u"单呼中...")
                    self.Btn_ptt.Enable(True)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

            if self.rtpSocket == None:
                log.TestLog(u"创建连接插件的rtpSocket")
                self.rtpSocket = rtpSocket(self.cpu, self.cpu["data"]._const["RTPWS"]["CONFIG"]["HOST"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PORT"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PATH"])

            times = 0
            while True:
                if (self.rtpSocket.statCon == True):
                    log.TestLog(u"开始连接语音插件...")
                    log.TestLog("cid:" + str(self.websocket.cid) + "\tsid:" + str(self.websocket.sid) + "\taport:" + str(self.websocket.aport))
                    self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, "120.27.201.238", self.websocket.aport, 3, 1)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == True):
                    log.TestLog(u"连接语音插件成功...")
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)
        else:
            log.TestLog(u"开始退出语音频道")
            self.websocket.wsTcpSend(assemblyTCPData(4, 1, 1, getOutVoiceChannelMsg(self.cmpid, self.uid)))

            times = 0
            while True:
                if (self.websocket.statInChannel == False):
                    log.TestLog(u"已经退出语音频道，开始结束单呼...")
                    self.websocket.wsTcpSend(assemblyTCPData(5, 1, 1, getVideoSingleCallHangUpMsg(self.websocket.cid,self.websocket.sid,self.gid, self.uid)))
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if(self.websocket.statSingleCall == False):
                    log.TestLog(u"单呼已经结束，开始关闭插件连接...")
                    log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
                    self.rtpSocket.stopSendRtp(self.websocket.sid, self.websocket.cid)
                    self.Btn_singleCall.SetBackgroundColour("#398bfb")
                    self.Btn_singleCall.SetLabel(u"单呼")
                    self.Btn_ptt.Enable(False)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

    def OnBtn_temporaryGroupClick(self, event):
        if self.Btn_temporaryGroup.GetLabel() == u"临时组":
            log.TestLog(u"模拟调度台开始发起临时组对讲...")
            log.TestLog(u"开始创建临时组")
            tempIdArray = []
            for member in self.selectMemberList:
                tempIdArray.append(str(member))
            self.tempGroupId = ','.join(tempIdArray)

            response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/group/createTemporaryGroup.do', getCreateTemporaryGroupMsg(self.uid, self.userType, self.cmpid, self.key, self.cpu["data"]._const["TEMPGROUP_TYPE"]["tempGroup"], self.tempGroupId))
            if response["status"] ==  'success':
                self.gid = response["content"]["body"]
                log.TestLog(u"临时组创建成功...")
            else:
                log.TestLog(u"临时组创建失败...")
                return

            log.TestLog(u"发起临时组对讲")
            log.TestLog("groupid:"+str(self.groupId)+"\tgid:"+str(self.gid))
            self.websocket.wsTcpSend(assemblyTCPData(20, 1, 1, getTemporaryTalkMsg(self.cmpid, self.uid, self.gid)))

            times = 0
            while True:
                if (self.websocket.statTempGroup == True):
                    log.TestLog(u"临时对讲发起成功，开始进入语音频道...")
                    self.websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(self.cmpid, self.uid, self.gid, self.cpu["data"]._const["CHANNEL_TYPE"]["tempGroup"])))
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if(self.websocket.statInChannel == True):
                    log.TestLog(u"成功进入语音频道")
                    self.Btn_temporaryGroup.SetBackgroundColour("#ff0000")
                    self.Btn_temporaryGroup.SetLabel(u"临时组中...")
                    self.Btn_ptt.Enable(True)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

            if self.rtpSocket == None:
                log.TestLog(u"创建连接插件的rtpSocket")
                self.rtpSocket = rtpSocket(self.cpu, self.cpu["data"]._const["RTPWS"]["CONFIG"]["HOST"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PORT"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PATH"])

            times = 0
            while True:
                if (self.rtpSocket.statCon == True):
                    log.TestLog(u"开始连接语音插件...")
                    log.TestLog("cid:" + str(self.websocket.cid) + "\tsid:" + str(self.websocket.sid) + "\taport:" + str(self.websocket.aport))
                    self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, "120.27.201.238", self.websocket.aport, 3, 1)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == True):
                    log.TestLog(u"连接语音插件成功...")
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

        else:
            log.TestLog(u"开始退出语音频道")
            self.websocket.wsTcpSend(assemblyTCPData(4, 1, 1, getOutVoiceChannelMsg(self.cmpid, self.uid)))

            times = 0
            while True:
                if (self.websocket.statInChannel == False):
                    log.TestLog(u"已经退出语音频道，开始结束临时组...")
                    self.websocket.wsTcpSend(assemblyTCPData(22, 1, 1, getTemporaryTalkHangUpMsg(self.websocket.cid, self.websocket.sid, self.gid, self.uid)))
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if(self.websocket.statTempGroup == False):
                    log.TestLog(u"临时组已经结束，开始关闭插件连接...")
                    log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
                    self.rtpSocket.stopSendRtp(self.websocket.sid, self.websocket.cid)
                    self.Btn_temporaryGroup.SetBackgroundColour("#398bfb")
                    self.Btn_temporaryGroup.SetLabel(u"临时组")
                    self.Btn_ptt.Enable(False)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

    def OnBtn_broadcastClick(self, event):
        if self.Btn_broadcast.GetLabel() == u"广播":
            log.TestLog(u"模拟调度台发起广播...")
            log.TestLog(u"开始创建临时组...")
            broadcastIdArray = []
            for group in self.groupList:
                broadcastIdArray.append(str(group["groupId"]))
            self.broadcastId = ','.join(broadcastIdArray)

            response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/group/createTemporaryGroup4Broadcast.do', getCreateTemporaryGroup4Broadcast(self.uid, self.userType, self.cmpid, self.key, self.cpu["data"]._const["TEMPGROUP_TYPE"]["boardCast"], self.broadcastId))
            if response["status"] ==  'success':
                self.gid = response["content"]["body"]
                log.TestLog(u"临时组创建成功...")
            else:
                log.TestLog(u"临时组创建失败...")
                return

            log.TestLog(u"开始发起广播...")
            log.TestLog("gid:"+str(self.gid))
            self.websocket.wsTcpSend(assemblyTCPData(16,1,1,getBoardcastMsg(self.cmpid, self.gid, self.uid)))

            times = 0
            while True:
                if (self.websocket.statBroadcast == True):
                    log.TestLog(u"广播发起成功，开始进入语音频道...")
                    self.websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(self.cmpid, self.uid, self.gid, self.cpu["data"]._const["CHANNEL_TYPE"]["broadcast"])))
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if(self.websocket.statInChannel == True):
                    log.TestLog(u"成功进入语音频道")
                    self.Btn_broadcast.SetBackgroundColour("#ff0000")
                    self.Btn_broadcast.SetLabel(u"广播中...")
                    self.Btn_ptt.Enable(True)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

            if self.rtpSocket == None:
                log.TestLog(u"创建连接插件的rtpSocket")
                self.rtpSocket = rtpSocket(self.cpu, self.cpu["data"]._const["RTPWS"]["CONFIG"]["HOST"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PORT"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PATH"])

            times = 0
            while True:
                if (self.rtpSocket.statCon == True):
                    log.TestLog(u"rtpSocket创建成功,开始连接语音插件...")
                    log.TestLog("cid:" + str(self.websocket.cid) + "\tsid:" + str(self.gid) + "\taport:" + str(self.websocket.aport))
                    #self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, "120.27.201.238", self.websocket.aport, 3, 1)
                    self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, str(self.websocket.aip), self.websocket.aport, 3, 1)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == True):
                    log.TestLog(u"连接语音插件成功...")
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

        else:
            log.TestLog(u"开始退出语音频道")
            self.websocket.wsTcpSend(assemblyTCPData(4, 1, 1, getOutVoiceChannelMsg(self.cmpid, self.uid)))

            times = 0
            while True:
                if (self.websocket.statInChannel == False):
                    log.TestLog(u"已经退出语音频道，开始结束广播...")
                    self.websocket.wsTcpSend(assemblyTCPData(18, 1, 1, getBoardcastHangUpMsg(self.websocket.cid, self.websocket.sid, self.gid, self.uid)))
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if(self.websocket.statBroadcast == False):
                    log.TestLog(u"广播已经结束，开始关闭插件连接...")
                    log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
                    self.rtpSocket.stopSendRtp(self.websocket.sid, self.websocket.cid)
                    self.Btn_broadcast.SetBackgroundColour("#398bfb")
                    self.Btn_broadcast.SetLabel(u"广播")
                    self.Btn_ptt.Enable(False)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times+=1
                    time.sleep(0.001)

    def OnBtn_pttClick(self, event):
        if self.Btn_ptt.GetLabel() == u"发送语音":
            log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
            self.rtpSocket.startSendRtp(self.websocket.sid, self.websocket.cid, 1)
            self.Btn_ptt.SetBackgroundColour("#ff0000")
            self.Btn_ptt.SetLabel(u"语音中...")
        else:
            log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
            self.rtpSocket.startSendRtp(self.websocket.sid, self.websocket.cid, 0)
            self.Btn_ptt.SetBackgroundColour("#398bfb")
            self.Btn_ptt.SetLabel(u"发送语音")

# 终端模拟
class panel_terminal_simulation(wx.Panel):
    def __init__(self, parent, cpu, username, password, pos=(0,0), size=(800,450)):
        self.cpu = cpu
        self.username = username
        self.password = password
        self.uid = 0
        self.gid = 0
        self.companyName = u''
        self.defaultGroupId = 0
        self.defaultGroupName = u""
        self.groupId = 0
        self.cmpid = 0
        self.key = ''
        self.groupList = ""
        self.memberList = ""
        self.singleCallId = 0
        self.tempGroupId = 0
        self.selectMemberList = {}
        self.userType = 2
        self.websocket = None
        self.rtpSocket = None

        wx.Panel.__init__(self, parent, -1, pos, size, style=wx.BORDER_DOUBLE)
        self.SetBackgroundColour("#f1f1f1")
        font_bold = wx.Font(16, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        font_12 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        font_16 = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.SetFont(font_12)
        self.title = StaticLabel(self, -1, u"模拟无屏终端", font=font_bold, color='#ffffff', bgColor="#777777", pos=(0,0),size=(800,30))
        self.Label_username = StaticLabel(self, -1, u"账号：", color="#ffffff", bgColor="#4ebaf8", pos=(0,32), size=(100,30))
        self.TextCtrl_username = wx.TextCtrl(self, -1, self.username, pos=(100,32), size=(200,30), style=wx.TE_RICH)
        self.Label_password = StaticLabel(self, -1, u"密码：", color="#ffffff", bgColor="#2fa7ee", pos=(300,32), size=(100,30))
        self.TextCtrl_password = wx.TextCtrl(self, -1, self.password, pos=(400,32), size=(200,30), style=wx.TE_RICH)
        self.Btn_login = ButtonWord(self, -1, u"登录", color="#ffffff", bgColor="#398bfb", pos=(605, 32), size=(190, 30))

        self.Label_groupList = StaticLabel(self, -1, u"群组列表：", bgColor="#4ebaf8", pos=(0, 64), size=(250, 30))
        self.ListBox_groupList = wx.ListBox(self, -1, (0,96), (505, 350), '', wx.LB_SINGLE)

        self.Label_devStatus = StaticLabel(self, -1, u"语音频道：", bgColor="#4ebaf8", pos=(255, 64), size=(250, 30))
        self.Label_groupInfo = StaticLabel(self, -1, u"默认组", color="#ffffff", bgColor="#767676", pos=(510,66), size=(290,30),align="center")
        self.Btn_switchChannel = ButtonWord(self, -1, u"切换频道", color="#ffffff", bgColor="#398bfb", pos=(510, 200), size=(290,30))
        self.Btn_exitChannel = ButtonWord(self, -1, u"退出语音频道", color="#ffffff", bgColor="#398bfb", pos=(510, 250), size=(290,30))
        self.Btn_ptt = ButtonWord(self, -1, u"发送语音", color="#ffffff", bgColor="#398bfb", pos=(510,400), size=(290,30))


        self.TextCtrl_username.SetFont(font_16)
        self.TextCtrl_password.SetFont(font_16)
        self.Btn_login.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_switchChannel.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_ptt.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

        self.Btn_switchChannel.Enable(False)
        self.Btn_exitChannel.Enable(False)
        self.Btn_ptt.Enable(False)

        self.Bind(wx.EVT_BUTTON, self.OnBtn_loginClick, self.Btn_login)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_switchChannelClick, self.Btn_switchChannel)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_exitChannelClick, self.Btn_exitChannel)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_pttClick, self.Btn_ptt)

    def OnBtn_loginClick(self, event):
        if self.Btn_login.GetLabel() == u"已登录":
            log.TestLog(u"账号已经登录...","F")
            return
        log.TestLog(u"模拟无屏终端开始登录...")
        self.username = self.TextCtrl_username.GetValue()
        self.password = self.TextCtrl_password.GetValue()
        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/login.do', getLoginMsg(self.username, self.password, self.userType))

        if response["status"] == 'success':
            self.uid = response["content"]["body"]["userid"]
            self.cmpid = response["content"]["body"]["companyId"]
            self.defaultGroupId = response["content"]["body"]["defaultGroupId"]
            self.companyName = response["content"]["body"]["companyName"]
            self.key = response["content"]["body"]["userToken"]
            #self.Btn_login.SetBackgroundColour("#ff0000")
            #self.Btn_login.SetLabel(u"已登录")
            #self.Btn_login.Refresh()
            log.TestLog(u"模拟无屏终端登录成功...")
        else:
            return
        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/groupQuery.do', getGroupQueryMsg(self.uid, self.cmpid, self.userType, '', self.key))
        if response["status"] == 'success':
            self.ListBox_groupList.Clear()
            self.groupList = json.loads(response["content"]["body"])
            for group in self.groupList:
                self.ListBox_groupList.Append(group["groupName"])
            log.TestLog("defaultGroupId:"+str(self.defaultGroupId))
            if self.defaultGroupId == 0:
                self.defaultGroupName = u"无群组"
                #self.Label_groupInfo.SetLabel(u"无群组")
            else:
                log.TestLog("defaultName:"+group["groupName"])
                self.defaultGroupName = group["groupName"]
                #self.ListBox_groupList.SetStringSelection(group["groupName"], True)

        log.TestLog(u"开始建立Websocket来进行TCP通信")
        self.websocket = webSocket(self.cpu, self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["WS"]["CONFIG"]["PORT"], 'fn-ws', self.cmpid, self.uid, self.password, self.key)
        #log.info(u"发起TCP接入请求1——>8001")
        times = 0
        while True:
            if(self.websocket.statCon == True):
                log.TestLog(u"Websocket创建成功，开始发起TCP接入请求...")
                self.websocket.wsTcpSend(assemblyTCPData(1, 1, 1, getAccessMsg(self.cmpid, self.uid, md5(self.password), self.userType, FN_KEY)))
                break
            else:
                if times > 2000:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        #log.info(u"创建心跳线程2——>8002")
        times = 0
        while True:
            if(self.websocket.statTcpIn == True):
                log.TestLog(u"TCP接口成功，开启心跳线程...")
                thread_heartbeat = threading.Thread(target=heartbeat, args=(self.websocket, self.cmpid, self.uid, self.websocket.token))
                thread_heartbeat.start()
                break
            else:
                if times > 2000:
                    if(self.websocket.statHasChannel == True):
                        log.TestLog(u"对讲终端已经在通话中，暂时不能重新登录...")
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        log.TestLog(u"账号成功登录，开始调整控件显示...")
        self.Btn_switchChannel.Enable(True)
        self.Btn_exitChannel.Enable(True)
        self.Btn_ptt.Enable(True)

        self.Btn_login.SetBackgroundColour("#ff0000")
        self.Btn_login.SetLabel(u"已登录")
        self.Label_groupInfo.SetLabel(self.defaultGroupName)
        log.TestLog(u"账号成功登录，结束调整控件显示...")

        if self.defaultGroupId != 0:
            log.TestLog(u"默认群组非空，开始发起进入语音频道的请求")
            self.websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(self.cmpid, self.uid, self.defaultGroupId,self.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
        else:
            log.TestLog(u"默认群组为空")
            return

        times = 0
        while True:
            if(self.websocket.statInChannel == True):
                log.TestLog(u"成功进入语音频道"+self.defaultGroupName)
                self.Label_groupInfo.SetLabel(self.defaultGroupName)
                break
            else:
                if times > 2000:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        if self.rtpSocket == None:
            log.TestLog(u"创建连接插件的rtpSocket")
            self.rtpSocket = rtpSocket(self.cpu, self.cpu["data"]._const["RTPWS"]["CONFIG"]["HOST"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PORT"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PATH"])

            times = 0
            while True:
                if (self.rtpSocket.statCon == True):
                    log.TestLog(u"开始连接语音插件...")
                    log.TestLog("cid:" + str(self.websocket.cid) + "\tsid:" + str(self.websocket.sid) + "\taport:" + str(self.websocket.aport))
                    self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, str(self.websocket.aip), self.websocket.aport, 3, 1)
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == True):
                    log.TestLog(u"连接语音插件成功...")
                    break
                else:
                    if times > 2000:
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

    def OnBtn_switchChannelClick(self, event):
        log.TestLog(u"开始进行群组切换...")
        groupName = self.ListBox_groupList.GetStringSelection()
        if groupName == "":
            log.TestLog(u"没有选择起切换的群组，请确认...")
            return
        for group in self.groupList:
            if groupName == group["groupName"]:
                self.defaultGroupId = group["groupId"]
                self.defaultGroupName = group["groupName"]
        log.TestLog(u"开始进入群组:"+self.defaultGroupName+u"其编号为："+str(self.defaultGroupId))
        self.websocket.wsTcpSend(assemblyTCPData(3, 1, 1,getInVoiceChannelMsg(self.cmpid, self.uid, self.defaultGroupId,self.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))

        times = 0
        while True:
            if(self.websocket.statInChannel == True):
                log.TestLog(u"成功进入语音频道"+groupName)
                break
            else:
                if times > 2000:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        if self.rtpSocket == None:
            log.TestLog(u"创建rtpSocket")
            self.rtpSocket = rtpSocket(self.cpu, self.cpu["data"]._const["RTPWS"]["CONFIG"]["HOST"], self.cpu["data"]._const["RTPWS"]["CONFIG"]["PORT"], self.cpu["data"]._const["RTPWS"]["CONFIG"]["PATH"])

        times = 0
        while True:
            if (self.rtpSocket.statCon == True):
                log.TestLog(u"rtpSocket创建成功，开始连接语音插件...")
                log.TestLog("cid:" + str(self.websocket.cid) + "\tsid:" + str(self.websocket.sid) + "\taport:" + str( self.websocket.aport)+"\taip:"+str(self.websocket.aip))
                self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, str(self.websocket.aip), self.websocket.aport, 3, 1)
                #self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, "120.27.201.238", self.websocket.aport, 3, 1)
                break
            else:
                if times > 2000:
                    log.TestLog(u"rtpSocket创建失败...","F")
                    self.Label_groupInfo.SetLabel(groupName)
                    return -1
                else:
                    times += 1
                time.sleep(0.001)

        times = 0
        while True:
            if (self.rtpSocket.statRtpIn == True):
                log.TestLog(u"语音插件连接成功...")
                break
            else:
                if times > 2000:
                    log.TestLog(u"语音插件连接失败...","F")
                    self.Label_groupInfo.SetLabel(groupName)
                    return -1
                else:
                    times += 1
                time.sleep(0.001)

        self.Label_groupInfo.SetLabel(groupName)

    def OnBtn_exitChannelClick(self, event):
        if (self.cmpid and self.uid):
            log.TestLog(u"开始退出语音频道...")
            self.websocket.wsTcpSend(assemblyTCPData(4, 1, 1, getOutVoiceChannelMsg(self.cmpid, self.uid)))

            times = 0
            while True:
                if (self.websocket.statInChannel == False):
                    log.TestLog(u"已成功退出语音频道...")
                    break
                else:
                    if times > 2000:
                        log.TestLog(u"退出语音频道失败...","F")
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            log.TestLog(u"开始关闭RTP发送通道...")
            self.rtpSocket.stopSendRtp(self.websocket.sid, self.websocket.cid)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == False):
                    log.TestLog(u"已成功关闭，RTP发送通道...")
                    break
                else:
                    if times > 2000:
                        log.TestLog(u"关闭RTP发送通道失败...","F")
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)
        else:
            log.TestLog(u"没有语音频道的数据信息，无须退出...")
            return

    def OnBtn_pttClick(self, event):
        log.TestLog(u"开始发送语音...")
        if self.Btn_ptt.GetLabel() == u"发送语音":
            log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
            self.rtpSocket.startSendRtp(self.websocket.sid, self.websocket.cid, 1)
            self.Btn_ptt.SetBackgroundColour("#ff0000")
            self.Btn_ptt.SetLabel(u"语音中...")
        else:
            log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
            self.rtpSocket.startSendRtp(self.websocket.sid, self.websocket.cid, 0)
            self.Btn_ptt.SetBackgroundColour("#398bfb")
            self.Btn_ptt.SetLabel(u"发送语音")

# 对讲模拟
class panel_intercom_simulation(wx.Panel):
    def __init__(self, parent, cpu, username, password, localIP, localPort, pos=(0,0), size=(250,190)):
        self.cpu = cpu
        self.username = username
        self.password = password
        self.localIP = localIP
        self.localPort = localPort
        self.uid = 0
        self.gid = 0
        self.companyName = u''
        self.defaultGroupId = 0
        self.defaultGroupName = u""
        self.groupId = 0
        self.cmpid = 0
        self.key = ''
        self.groupList = ""
        self.memberList = ""
        self.singleCallId = 0
        self.tempGroupId = 0
        self.selectMemberList = {}
        self.userType = 2
        self.websocket = None
        self.rtpSocket = None

        wx.Panel.__init__(self, parent, -1, pos, size, style=wx.BORDER_DOUBLE)
        self.SetBackgroundColour("#f1f1f1")
        font_12 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        font_14 = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.SetFont(font_12)

        self.title = StaticLabel(self, -1, u"模拟无屏终端", font=font_14, color='#ffffff', bgColor="#777777", pos=(0,0),size=(250,30))
        self.Label_username     = StaticLabel(self, -1, u"账号：", color="#ffffff", bgColor="#4ebaf8", pos=(0,30), size=(100,30))
        self.TextCtrl_username  = wx.TextCtrl(self, -1, self.username, pos=(100,30), size=(150,30), style=wx.TE_RICH)
        self.Label_password     = StaticLabel(self, -1, u"密码：", color="#ffffff", bgColor="#2fa7ee", pos=(0,61), size=(100,30))
        self.TextCtrl_password  = wx.TextCtrl(self, -1, self.password, pos=(100,61), size=(150,30), style=wx.TE_RICH)
        self.Label_channel      = StaticLabel(self, -1, u"频道：", color="#ffffff", bgColor="#2fa7ee", pos=(0,92), size=(100,30))
        self.Label_channelInfo  = StaticLabel(self, -1, u"默认组", color="#0000ff", bgColor="#ffffff", pos=(100,92), size=(150, 30))

        self.Btn_switchChannel  = ButtonWord(self, -1, u"切换频道", color="#ffffff", bgColor="#398bfb", pos=(0, 123), size=(124, 30))
        self.Btn_ptt            = ButtonWord(self, -1, u"发送语音", color="#ffffff", bgColor="#398bfb", pos=(126, 123), size=(124, 30))
        self.Btn_login          = ButtonWord(self, -1, u"登录", color="#ffffff", bgColor="#398bfb", pos=(0, 154), size=(124, 30))
        self.Btn_exit           = ButtonWord(self, -1, u"退出", color="#ffffff", bgColor="#398bfb", pos=(126, 154), size=(124, 30))

        self.TextCtrl_username.SetFont(font_14)
        self.TextCtrl_password.SetFont(font_14)

        self.Btn_switchChannel.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_ptt.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_login.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.Btn_exit.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

        self.Btn_switchChannel.Enable(False)
        self.Btn_ptt.Enable(False)
        self.Btn_exit.Enable(False)

        self.Bind(wx.EVT_BUTTON, self.OnBtn_login, self.Btn_login)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_switchChannelClick, self.Btn_switchChannel)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_exit, self.Btn_exit)
        self.Bind(wx.EVT_BUTTON, self.OnBtn_pttClick, self.Btn_ptt)

    def OnBtn_switchChannelClick(self, event):
        log.TestLog(u"模拟对讲机开始切换语音频道")
        pass

    def OnBtn_pttClick(self, event):
        log.TestLog(u"开始发送语音...")
        if self.Btn_ptt.GetLabel() == u"发送语音":
            log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
            self.rtpSocket.startSendRtp(self.websocket.sid, self.websocket.cid, 1)
            self.Btn_ptt.SetBackgroundColour("#ff0000")
            self.Btn_ptt.SetLabel(u"语音中...")
        else:
            log.TestLog("sid:" + str(self.websocket.sid) + "\tcid:" + str(self.websocket.cid))
            self.rtpSocket.startSendRtp(self.websocket.sid, self.websocket.cid, 0)
            self.Btn_ptt.SetBackgroundColour("#398bfb")
            self.Btn_ptt.SetLabel(u"发送语音")

    def OnBtn_login(self, event):
        log.TestLog(u"模拟对讲机开始登录...")
        self.Btn_exit.Enable(True)
        self.Btn_switchChannel.Enable(True)
        self.Btn_ptt.Enable(True)
        self.Btn_login.Enable(False)
        log.TestLog(u"账号："+str(self.TextCtrl_username.GetValue())+u"\t密码："+str(self.TextCtrl_password.GetValue()))


        log.TestLog(u"模拟对讲机开始登录...")
        self.username = self.TextCtrl_username.GetValue()
        self.password = self.TextCtrl_password.GetValue()
        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/login.do', getLoginMsg(self.username, self.password, self.userType))

        if response["status"] == 'success':
            self.uid = response["content"]["body"]["userid"]
            self.cmpid = response["content"]["body"]["companyId"]
            self.defaultGroupId = response["content"]["body"]["defaultGroupId"]
            self.companyName = response["content"]["body"]["companyName"]
            self.key = response["content"]["body"]["userToken"]
            #self.Btn_login.SetBackgroundColour("#ff0000")
            #self.Btn_login.SetLabel(u"已登录")
            #self.Btn_login.Refresh()
            log.TestLog(u"模拟无屏终端登录成功...")
        else:
            return

        response = fnHttpPost_app(self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], self.cpu["data"]._const["HTTP"]["PORT"], '/fn/app/groupQuery.do', getGroupQueryMsg(self.uid, self.cmpid, self.userType, '', self.key))
        if response["status"] == 'success':
            self.groupList = json.loads(response["content"]["body"])
            if self.defaultGroupId == 0:
                self.defaultGroupName = u"无群组"
            else:
                for group in self.groupList:
                    if self.defaultGroupId == group["groupId"]:
                        self.defaultGroupName = group["groupName"]

        log.TestLog(u"开始建立Websocket来进行TCP通信")
        self.websocket = webSocket(self.cpu, self.cpu["data"]._const["WS"]["CONFIG"]["HOST"], 8087, 'fn-ws', self.cmpid, self.uid, self.password, self.key)
        #log.info(u"发起TCP接入请求1——>8001")
        times = 0
        while True:
            if(self.websocket.statCon == True):
                log.TestLog(u"Websocket创建成功，开始发起TCP接入请求...")
                self.websocket.wsTcpSend(assemblyTCPData(1, 1, 1, getAccessMsg(self.cmpid, self.uid, md5(self.password), self.userType, FN_KEY)))
                break
            else:
                if times > 2000:
                    log.TestLog(u"Websocket创建失败...")
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        #log.info(u"创建心跳线程2——>8002")
        times = 0
        while True:
            if(self.websocket.statTcpIn == True):
                log.TestLog(u"TCP接口成功，开启心跳线程...")
                thread_heartbeat = threading.Thread(target=heartbeat, args=(self.websocket, self.cmpid, self.uid, self.websocket.token))
                thread_heartbeat.start()
                break
            else:
                if times > 2000:
                    if(self.websocket.statHasChannel == True):
                        log.TestLog(u"对讲终端已经在通话中，暂时不能重新登录...")
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        if self.defaultGroupId != 0:
            log.TestLog(u"默认群组非空，开始发起进入语音频道的请求")
            self.websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(self.cmpid, self.uid, self.defaultGroupId,self.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
        else:
            log.TestLog(u"默认群组为空")
            return

        times = 0
        while True:
            if(self.websocket.statInChannel == True):
                log.TestLog(u"成功进入语音频道"+self.defaultGroupName)
                self.Label_channelInfo.SetLabel(self.defaultGroupName)
                self.cpu["data"]._const["simulationTest"]["bakIntercomGroup"] = self.defaultGroupId
                break
            else:
                if times > 2000:
                    log.TestLog(u"进入语音频道失败...")
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        if self.rtpSocket == None:
            log.TestLog(u"创建连接插件的rtpSocket")
            self.rtpSocket = rtpSocket(self.cpu, self.cpu["data"]._const["RTPWS"]["CONFIG"]["HOST"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PORT"],self.cpu["data"]._const["RTPWS"]["CONFIG"]["PATH"],self.localIP,self.localPort)

            times = 0
            while True:
                if (self.rtpSocket.statCon == True):
                    log.TestLog(u"RtpSocket创建成功，开始连接语音插件...")
                    log.TestLog("cid:" + str(self.websocket.cid) + "\tsid:" + str(self.websocket.sid) + "\taport:" + str(self.websocket.aport))
                    self.rtpSocket.accessRtp(self.websocket.cid, self.websocket.sid, self.uid, str(self.websocket.aip), self.websocket.aport, 3, 1)
                    break
                else:
                    if times > 2000:
                        log.TestLog(u"RtpSocket创建失败...")
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == True):
                    log.TestLog(u"连接语音插件成功...")
                    break
                else:
                    if times > 2000:
                        log.TestLog(u"连接语音插件失败...")
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

        log.TestLog(u"账号成功登录，开始调整控件显示...")
        self.Btn_exit.Enable(True)
        self.Btn_switchChannel.Enable(True)
        self.Btn_ptt.Enable(True)
        self.Btn_login.Enable(False)

        self.Btn_login.SetLabel(u"已登录")
        self.Label_channelInfo.SetLabel(self.defaultGroupName)
        log.TestLog(u"账号成功登录，结束调整控件显示...")

    def OnBtn_exit(self, event):
        log.TestLog(u"模拟对讲机开始退出登录...")

        if (self.cmpid and self.uid):
            log.TestLog(u"开始退出语音频道...")
            self.websocket.wsTcpSend(assemblyTCPData(4, 1, 1, getOutVoiceChannelMsg(self.cmpid, self.uid)))

            times = 0
            while True:
                if (self.websocket.statInChannel == False):
                    log.TestLog(u"已成功退出语音频道...")
                    break
                else:
                    if times > 2000:
                        log.TestLog(u"退出语音频道失败...","F")
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)

            log.TestLog(u"开始关闭RTP发送通道...")
            self.rtpSocket.stopSendRtp(self.websocket.sid, self.websocket.cid)

            times = 0
            while True:
                if (self.rtpSocket.statRtpIn == False):
                    log.TestLog(u"已成功关闭，RTP发送通道...")
                    break
                else:
                    if times > 2000:
                        log.TestLog(u"关闭RTP发送通道失败...","F")
                        return -1
                    else:
                        times += 1
                    time.sleep(0.001)
        else:
            log.TestLog(u"没有语音频道的数据信息，无须退出...")
            return

        self.Btn_exit.Enable(False)
        self.Btn_switchChannel.Enable(False)
        self.Btn_ptt.Enable(False)
        self.Btn_login.Enable(True)
        self.Btn_login.SetLabel(u"登录")
        self.Btn_login.SetBackgroundColour("#398bfb")